<?php

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-21
 * Time: 10:36:43
 * Info:
 */

namespace app\admin\controller;

use app\common\model\Admin as AdminModel;
use app\common\model\LoginLog as LoginLogModel;
use app\common\model\Message as MessageModel;
use app\common\model\SystemLog as SystemLogModel;
use app\common\model\UploadGroup as UploadGroupModel;
use app\common\service\MenuService;
use support\Request;
use think\facade\Cache;
use think\facade\Db;

class IndexController extends CommonController
{

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            return $this->success('login ok');
        }
        $adminId = cmf_get_admin_id();

        return view('index', ['admin_id' => $adminId]);
    }

    public function welcome(Request $request)
    {
        $id         = cmf_get_admin_id();
        $admin_info = AdminModel::alias('a')->leftJoin('auth_group ag',
            'ag.id=a.role_id')->field('ag.name as group_name,a.*')->where('a.id', $id)->find()->toArray();
        if (empty($admin_info)) {
            return error_json('login!!!');
        }

        return view('welcome', ['admin_info' => $admin_info, 'sys_info' => $this->get_sys_info()]);
    }

    public function edit_info(Request $request)
    {
        $id   = cmf_get_admin_id();
        $data = AdminModel::find($id);

        if ($request->isPost()) {
            $param = $request->all();
            $res   = $data->save($param);
            if ($res) {
                return $this->success('保存成功');
            } else {
                return error_json('保存失败');
            }
        }

        return view('admin/edit_info', ['data' => $data]);
    }

    public function login_log(Request $request)
    {
        $id = cmf_get_admin_id();
        if ($request->isAjax()) {
            $limit = (int)$request->input('limit', 10);
            $page  = (int)$request->input('page', 1);
            $first = ($page - 1) * $limit;
            $count = LoginLogModel::where('user_id', $id)->count();
            $list  = LoginLogModel::where('user_id', $id)->limit($first, $limit)->order('id desc')->select();
            foreach ($list as $key => $v) {
                $area = ! empty($v['area']) ? "-".$v['area'] : "";
                $city = ! empty($v['city']) ? "-".$v['city'] : "";

                $list[$key]['address'] = $v['country'].$area.$city;
                $list[$key]['status']  = strstr($v['desc'], 'success') ? 1 : 0;
            }

            return $this->success('ok', $list, $count);
        }
    }

    public function system_log(Request $request)
    {
        $id = cmf_get_admin_id();
        if ($request->isAjax()) {
            $limit = (int)$request->input('limit', 10);
            $page  = (int)$request->input('page', 1);
            $first = ($page - 1) * $limit;
            $count = SystemLogModel::where('admin_id', $id)->count();
            $list  = SystemLogModel::where('admin_id', $id)->limit($first, $limit)->order('id desc')->select();

            return $this->success('ok', $list, $count);
        }
    }

    public function admin_menu(Request $request)
    {
        if ($request->isAjax()) {
            $adminId     = cmf_get_admin_id();
            $MenuService = new MenuService();
            if (Cache::get('cacheAdminMenuId'.$adminId)) {
                $menuJson = Cache::get('cacheAdminMenuId'.$adminId);
            } else {
                $menuJson = $MenuService->getMenuTree();
                //Cache::set('cacheAdminMenuId'.$adminId, $menuJson);
            }

            return $this->success('ok', $menuJson);
        }
    }

    /**
     * 清除缓存
     */
    public function cacheClear(Request $request)
    {
        Cache::clear();
        $huicmfConfig  = config('huicmf');
        $runTimeArr    = $huicmfConfig['runtime_dir'];
        $runTimePath   = runtime_path().DIRECTORY_SEPARATOR;
        $run_time_path = scandir($runTimePath);
        foreach ($run_time_path as $val) {
            if ( ! in_array($val, $runTimeArr)) {
                continue;
            }
            if ( ! is_dir($runTimePath.$val)) {
                continue;
            }
            $dir = $runTimePath.$val.'/';
            //先删除目录下的文件：
            $dh = opendir($dir);
            while ($file = readdir($dh)) {
                if ($file != "." && $file != "..") {
                    $fullPath = $dir.$file;
                    if ( ! is_dir($fullPath)) {
                        @unlink($fullPath);
                    } else {
                        dir_delete($fullPath);
                    }
                }
            }
            closedir($dh);
            @rmdir($runTimePath.$val.'/');
        }

        return $this->success('ok');
    }

    /**
     * 站内消息
     */
    public function message()
    {
        $message1 = MessageModel::where('is_read', 0)->where('type', 1)->order('id desc')->select()->toArray();
        $m1       = [];
        foreach ($message1 as $v) {
            $v1['id']     = $v['id'];
            $v1['avatar'] = 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png';
            $v1['title']  = $v['text'];
            $v1['time']   = word_time(strtotime($v['create_time']));
            $v1['form']   = 1;
            $m1[]         = $v1;
        }

        $message2 = MessageModel::where('is_read', 0)->where('type', 2)->order('id desc')->select()->toArray();
        $m2       = [];
        foreach ($message2 as $v) {
            $v1['id']     = $v['id'];
            $v1['avatar'] = 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png';
            $v1['title']  = $v['text'];
            $v1['time']   = word_time(strtotime($v['create_time']));
            $v1['form']   = 2;
            $m2[]         = $v1;
        }

        return view('message', ['message' => $m1, 'notice' => $m2]);
    }

    /**
     * 消息标记读
     */
    public function message_read(Request $request)
    {
        $type = $request->input('type');
        switch ($type) {
            case 'message':
                $type = 1;
                break;
            case 'notice':
                $type = 2;
                break;
        }
        MessageModel::where('type', $type)->data(['is_read' => 1, 'update_time' => time()])->update();

        return $this->success('已读');
    }


    /**
     * 上传图片多选框
     */
    public function file_list(Request $request)
    {
        $type       = $request->input('type', 'many');
        $select_id  = $request->input('select_id');
        $group_list = UploadGroupModel::select()->toArray();

        return view('file_list', [
            'type'       => $type,
            'select_id'  => $select_id,
            'group_list' => $group_list
        ]);
    }

    /**
     * 管理员退出登录
     * @return void
     */
    public function login_out(Request $request)
    {
        $adminId = cmf_get_admin_id();
        $session = $request->session();
        Cache::clear();
        $session->forget(['session_admin_id', 'admin_info_'.$adminId]);

        return $this->success('退出登录成功');
    }

    /**
     * phpinfo信息 按需显示在前台
     * @return array
     */
    public function get_sys_info()
    {
        $sys_info['os']              = PHP_OS; //操作系统
        $sys_info['web_server']      = ''; //服务器环境
        $sys_info['phpv']            = phpversion(); //php版本
        $sys_info['fileupload']      = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknown'; //文件上传限制
        $sys_info['memory_limit']    = ini_get('memory_limit'); //最大占用内存
        $sys_info['domain']          = request()->host(); //域名
        $sys_info['remaining_space'] = round((@disk_free_space(".") / (1024 * 1024)), 2).'M'; //剩余空间
        $sys_info['beijing_time']    = gmdate("Y年n月j日 H:i:s", time() + 8 * 3600); //北京时间
        $sys_info['time']            = date("Y年n月j日 H:i:s"); //服务器时间
        $mysqlinfo                   = Db::query("SELECT VERSION() as version");
        $sys_info['mysql_version']   = $mysqlinfo[0]['version'];
        if (function_exists("gd_info")) {
            //GD库版本
            $gd                 = gd_info();
            $sys_info['gdinfo'] = $gd['GD Version'];
        } else {
            $sys_info['gdinfo'] = "未知";
        }

        return $sys_info;
    }

}
